import React, { useEffect, useState } from "react";
import axios from "axios";
const Index = () => {
  const [list, setList] = useState([]);

  // 收入
  const value1 = list.reduce((p, n) => {
    if (n.price > 0) {
      return p + n.price;
    }
    return p;
  }, 0);
  // 支出
  const value2 = list.reduce((p, n) => {
    if (n.price < 0) {
      return p + +n.price;
    }
    return p;
  }, 0);
  // 小记
  const value3 = value1 + value2;

  const getList = async () => {
    const resp = await axios.get("/api/list1");
    console.log(resp.data.data);
    setList(resp.data.data);
  };

  const [title, setTitle] = useState("");
  const [price, setPrice] = useState("");
  const [datetime, setDatetime] = useState("");
  const [tip, setTip] = useState("");
  const submit = () => {
    const data = {
      title, price, datetime, tip,
      id: Math.random().toString().slice(2)
    }
   setList(list.concat(data))
  }
  useEffect(() => {
    getList();
  }, []);
  return (
    <div>
      <table>
        <thead>
          <tr>
            <th>账目</th>
            <th>费用</th>
            <th>日期</th>
            <th>备注</th>
          </tr>
        </thead>
        <tbody>
          {list.map((v) => {
            return (
              <tr key={v.id}>
                <td>{v.title}</td>
                <td>{v.price}</td>
                <td>{v.datetime}</td>
                <td>{v.tip}</td>
              </tr>
            );
          })}
        </tbody>
        <tfoot>
          <tr>
            <td>收入： {value1}</td>
            <td>支出： {value2}</td>
            <td>小记： {value3}</td>
          </tr>
        </tfoot>
      </table>

      <input
        type="text"
        placeholder="请输入账目"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
      />
      <input
        type="text"
        placeholder="请输入费用"
        value={price}
        onChange={(e) => setPrice(e.target.value)}
      />
      <input
        type="date"
        placeholder="请输入日期"
        value={datetime}
        onChange={(e) => setDatetime(e.target.value)}
      />
      <input
        type="text"
        placeholder="请输入备注"
        value={tip}
        onChange={(e) => setTip(e.target.value)}
      />

      <button onClick={() => submit()}>提交</button>
    </div>
  );
};

export default Index;
